﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using RSEngine.Core;
using RSEngine.Math;

using RSRenderer.Core;
using RSRenderer.Device;
using RSRenderer.Imaging;
using RSRenderer.OptimizedGeometry;
using RSRenderer.Renderer.Bucket;

#region Copyright (c) 2006, 2007, 2008, 2009 Render Studio Foundation. All rights reserved.

/*
 Copyright (c) 2006, 2007, 2008, 2009 Render Studio Foundation. All rights reserved.
 This work is copyrighted in its entirety. Permission to use "Render Studio"
 material may be granted only after we receive a written request from you,
 and you receive written permission from us.

 While Render Studio Foundation provides the information herein to anyone,
 we retain copyright on all code, text, graphic images, and other content.
 This means that you may not distribute the code, the text or graphics to others without the
 express written permission of Render Studio Foundation; "mirror" this information on your server
 without our permission; or modify or reuse the code, text or graphics on our servers.
 You may print copies of the information for your own personal use; and, you may reference
 the Service from your own documents. Any commercial use of this material is prohibited without
 the written permission of Render Studio Foundation. In all copies of this information, you must
 retain this notice and any other copyright notices originally included with such information.

 This material may be protected by U.S. and International Copyright laws, and you are legally
 bound by the copyright notices on those systems.

 "Render Studio" logos and other official symbols or graphics may not be used in connection with any
 product or service that has not been expressly authorized in advance in writing or in any manner
 that is likely to cause confusion among the users of this or other Web sites or among the public.
 All other seals, graphics or trademarks of organizations not affiliated with Render Studio Foundation
 that appear on this site are the property of their respective owners.

 Render Studio Foundation reserve all other rights. 
*/

#endregion

#region Render Studio Source Code Licence

/*
This license governs use of the Render Studio software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Summary

The source code is made available to view for reference purposes or to contribute to the project only. Developers may not distribute or modify the code for commercial or non-commercial purposes without express Agreement of Render Studio Foundation.

2. Definitions

The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
"Licensor" means the foundation "Render Studio Foundation".
"You" means the licensee of the software, who is not engaged in designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software.
"Your company" means the company you worked for when you downloaded the software.
"Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging and maintaining your products. For clarity, "reference use" does NOT include (a) the right to use the software for purposes of designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software, and (b) the right to distribute the software outside of your company.
"Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license.

3. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use.
(B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use.
4. Limitations
(A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks.
(B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
(C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

#endregion

namespace RSRenderer.Renderer
{

    #region BucketRenderer_Options

    sealed public class BucketRenderer_Options : RenderOptions
    {

        #region enum : Order

        /// <summary>
        /// Define the different ordering methods to render.
        /// </summary>
        public enum Order
        {
            Row,
            Column,
            Hilbert,
            Random
        }

        #endregion

        /// <summary>
        /// The size of a bucket.
        /// </summary>
        public int BucketSize = 32;

        /// <summary>
        /// Define in which order the buckets are rendered.
        /// </summary>
        public Order RenderingOrder = Order.Hilbert;

    }

    #endregion

    sealed public class BucketRenderer : Renderer
    {

        #region Variables

        private BucketRenderer_Options _options = new BucketRenderer_Options();

        //---- Threading
        private int _threadsCount = 0;
        private int _completed = 0;

        //---- The buckets
        private int _bucketSize;
        private Vector2[] _bucketCoordinates;
        private int _bucketIterator = 0;

        #endregion

        #region  Initialize

        override public bool Initialize(RenderOptions options, Scene scene, int width, int height)
        {
            base.Initialize(options, scene, width, height);

            if (options.Groups.ContainsKey("BucketRenderer"))
                _options = (BucketRenderer_Options)options.Groups["BucketRenderer"];
            else
                _options = new BucketRenderer_Options();

            //---- Compute the buckets coordinates
            _bucketSize = Math.Min(Math.Max(16, _options.BucketSize), 512);
            int numBucketsX = (ImageWidth + _bucketSize - 1) / _bucketSize;
            int numBucketsY = (ImageHeight + _bucketSize - 1) / _bucketSize;
            _bucketCoordinates = BuildBuckets(_options.RenderingOrder, numBucketsX, numBucketsY);

            return true;
        }

        #endregion

        #region BuildBuckets

        /// <summary>
        /// Computes the order in which each coordinate on the screen should be visited.
        /// </summary>
        private Vector2[] BuildBuckets(BucketRenderer_Options.Order order, int numBucketsX, int numBucketsY)
        {
            switch (order)
            {
                case BucketRenderer_Options.Order.Row:
                    return RowBucketOrder.BuildBuckets(numBucketsX, numBucketsY);
                case BucketRenderer_Options.Order.Column:
                    return RowBucketOrder.BuildBuckets(numBucketsX, numBucketsY);
                case BucketRenderer_Options.Order.Hilbert:
                    return HilbertBucketOrder.BuildBuckets(numBucketsX, numBucketsY);
                case BucketRenderer_Options.Order.Random:
                    return RandomBucketOrder.BuildBuckets(numBucketsX, numBucketsY);
            }

            return null;
        }

        #endregion

        #region Render

        override public void Render(DisplayDevice device)
        {
            Device = device;

            // Compute the number of threads
            //_threadsCount = Environment.ProcessorCount;
            _threadsCount = 1; // easier to debug

            // Notify the device that we start rendering
            Device.ImageBegin(ImageWidth, ImageHeight, _bucketSize);

            //---- Start the rendering threads
            _completed = 0;
            _bucketIterator = 0;
            IsCanceled = false;
            for (int index = 0; index < _threadsCount; index++)
            {
                RenderProcessor processor = new RenderProcessor(this, index);
                ThreadPool.QueueUserWorkItem(new WaitCallback(processor.Render));
            }
        }

        #endregion

        #region OnBucketRenderingEnd

        internal void OnBucketRenderingEnd()
        {
            _completed++;

            if (_completed == _threadsCount)
                OnRenderingEnd();
        }

        #endregion

        #region OnRenderingEnd

        private void OnRenderingEnd()
        {
            Device.ImageEnd();
        }

        #endregion

        #region StopRendering

        public void StopRendering()
        {
            _completed = _threadsCount;
            IsCanceled = true;

            OnRenderingEnd();
        }

        #endregion

        #region NextBucket

        /// <summary>
        /// Retreive the next bucket to render.
        /// Returns an invalid bucket if there is no more bucket.
        /// </summary>
        public Vector2 NextBucket()
        {
            lock (this)
            {
                if (_bucketIterator >= _bucketCoordinates.Length)
                    return Vector2.Invalid;

                return _bucketCoordinates[_bucketIterator++];
            }
        }

        #endregion

        #region RenderBucket

        internal void RenderBucket(Vector2 bucket)
        {
            //---- Compute the real bucket coordinates
            int x0 = (int)(bucket.x * _bucketSize);
            int y0 = (int)(bucket.y * _bucketSize);
            int bw = Math.Min(_bucketSize, ImageWidth - x0);
            int bh = Math.Min(_bucketSize, ImageHeight - y0);

            //---- Prepare the image
            Device.ImagePrepare(x0, y0, bw, bh);

            Colour[,] buffer = new Colour[bw, bh];

            for (int y = 0; y < bh; y++)
                for (int x = 0; x < bw; x++)
                {
                    IntersectionState intersections = new IntersectionState();
                    ShadingState state = _lightServer.ComputeRadiance(intersections, x0 + x, ImageHeight - 1 - (y0 + y), 0, 0, 0, 0);

                    if (state == null)
                    {
                        buffer[x, y].R = 0f;
                        buffer[x, y].G = 0f;
                        buffer[x, y].B = 0f;
                    }
                    else
                        buffer[x, y] = state.ResultColour;
                }

            //---- Update the device
            Device.ImageUpdate(x0, y0, bw, bh, buffer);
        }

        #endregion

    }

    #region RenderProcessor

    internal sealed class RenderProcessor
    {

        #region Variables

        private BucketRenderer _renderer;
        private int _index;

        #endregion

        #region Constructor

        internal RenderProcessor(BucketRenderer renderer, int index)
        {
            _renderer = renderer;
            _index = index;
        }

        #endregion

        #region Render

        internal void Render(object stateInfo)
        {
            while (true)
            {
                Vector2 bucket = _renderer.NextBucket();
                if (bucket.IsInvalid)
                {
                    _renderer.OnBucketRenderingEnd();
                    return;
                }

                // Render the current bucker
                _renderer.RenderBucket(bucket);

                // Notify
                _renderer.OnBucketRenderingEnd();

                // Is canceled ?
                if (_renderer.IsCanceled)
                {
                    _renderer.StopRendering();
                    return;
                }
            }
        }

        #endregion

    }

    #endregion

}
